// src/stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, getUserInfo, logout as logoutApi } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const roles = ref(JSON.parse(localStorage.getItem('roles') || '[]'))
  const permissions = ref(JSON.parse(localStorage.getItem('permissions') || '[]'))

  // 计算属性
  const hasToken = computed(() => !!token.value)
  const isLoggedIn = computed(() => hasToken.value && userInfo.value?.id)

  // 登录
  const doLogin = async (loginForm) => {
    try {
      console.log('🔐 执行登录请求', loginForm)
      const response = await login(loginForm)
      
      console.log('登录响应:', response)
      
      // 根据你的后端返回格式处理
      const responseData = response.data?.data || response.data || response
      const { access_token, refresh_token, user } = responseData
      
      if (access_token) {
        token.value = access_token
        userInfo.value = user || {}
        
        // 保存到本地存储
        localStorage.setItem('token', access_token)
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        
        if (refresh_token) {
          localStorage.setItem('refresh_token', refresh_token)
        }
        
        console.log('✅ 登录成功，用户信息:', userInfo.value)
        
        // 登录成功后立即获取用户完整信息（包含权限）
        try {
          await fetchUserInfo()
        } catch (error) {
          console.warn('获取用户权限信息失败，使用基础权限:', error)
        }
        
        return { success: true, message: response.message || '登录成功' }
      } else {
        throw new Error('未获取到访问令牌')
      }
    } catch (error) {
      console.error('❌ 登录失败:', error)
      return { 
        success: false, 
        message: error.response?.data?.message || error.message || '登录失败' 
      }
    }
  }

  // 获取用户信息（包含权限）
const fetchUserInfo = async () => {
  try {
    console.log('📋 获取用户信息')
    const response = await getUserInfo()
    
    console.log('获取用户信息响应:', response)
    
    // 🔥 适配后端返回的结构 response.data.data.user
    const userData = response.data?.data?.user || response.data?.user || response.data || response
    
    if (!userData || !userData.id) {
      throw new Error('获取用户信息失败')
    }
    
    userInfo.value = userData
    
    // 🔥 直接使用后端返回的角色和权限数据
    if (userData.roles && Array.isArray(userData.roles)) {
      roles.value = userData.roles
    } else {
      roles.value = []
    }
    
    if (userData.permissions && Array.isArray(userData.permissions)) {
      permissions.value = userData.permissions
    } else {
      permissions.value = []
    }
    
    // 保存到本地存储
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    localStorage.setItem('roles', JSON.stringify(roles.value))
    localStorage.setItem('permissions', JSON.stringify(permissions.value))
    
    console.log('✅ 用户信息获取成功:', {
      user: userInfo.value,
      roles: roles.value,
      permissions: permissions.value
    })
    
    return userInfo.value
  } catch (error) {
    console.error('❌ 获取用户信息失败:', error)
    throw error
  }
}

  // 处理用户权限数据
  const processUserPermissions = async (userData) => {
    try {
      console.log('🔍 处理用户权限数据:', userData)
      
      // 检查后端是否返回了角色信息
      if (userData.roles && Array.isArray(userData.roles) && userData.roles.length > 0) {
        console.log('📋 从后端获取到角色信息:', userData.roles)
        roles.value = userData.roles
        
        // 从角色中提取权限
        const allPermissions = new Set()
        
        userData.roles.forEach(role => {
          console.log(`🔍 处理角色:`, role)
          
          if (role.permissions && Array.isArray(role.permissions)) {
            role.permissions.forEach(permission => {
              // 根据Permission实体结构提取权限代码
              const permissionCode = permission.code || permission.permission_code
              if (permissionCode && (permission.status === 'active' || permission.status === 1)) {
                allPermissions.add(permissionCode)
                console.log(`✅ 添加权限: ${permissionCode}`)
              }
            })
          }
        })
        
        permissions.value = Array.from(allPermissions)
        console.log('📋 最终权限列表:', permissions.value)
      } else {
        // 🚨 当前情况：后端返回空角色数组，使用临时权限方案
        console.warn('⚠️ 后端返回空角色列表，使用临时权限方案')
        await assignTemporaryPermissions(userData)
      }
    } catch (error) {
      console.error('处理用户权限失败:', error)
      await assignTemporaryPermissions(userData)
    }
  }

  // 临时权限分配方案 - 针对你的用户数据
  const assignTemporaryPermissions = async (userData) => {
    console.log('🔧 分配临时权限...', userData)
    
    // 根据用户名判断权限级别
    const username = userData.username || userData.name
    const userId = userData.id
    
    // 华兴汇明网站管理员 - 给予超级管理员权限
    const isSuperAdmin = username === 'hxhmadmin' || userData.realname?.includes('管理员')
    const isAdmin = username === 'admin' || username?.includes('admin')
    
    if (isSuperAdmin) {
      console.log('🔧 分配超级管理员权限')
      // 超级管理员权限
      roles.value = [{
        id: 'r001',
        role_name: '超级管理员',
        role_code: 'super_admin',
        status: 'active'
      }]
      
      permissions.value = [
        // 系统管理
        'dashboard:read',
        'system:read', 'system:create', 'system:update', 'system:delete',
        
        // 用户管理
        'user:read', 'user:create', 'user:update', 'user:delete',
        
        // 角色权限管理
        'role:read', 'role:create', 'role:update', 'role:delete',
        'permission:read', 'permission:create', 'permission:update', 'permission:delete',
        'menu:read', 'menu:create', 'menu:update', 'menu:delete',
        
        // 内容管理
        'category:read', 'category:create', 'category:update', 'category:delete',
        'archives:read', 'archives:create', 'archives:update', 'archives:delete',
        'attachment:read', 'attachment:create', 'attachment:update', 'attachment:delete',
        
        // 系统设置
        'setting:read', 'setting:update',
        'logger:read', 'logger:delete'
      ]
    } else if (isAdmin) {
      console.log('🔧 分配管理员权限')
      // 普通管理员权限
      roles.value = [{
        id: 'r002',
        role_name: '管理员',
        role_code: 'admin',
        status: 'active'
      }]
      
      permissions.value = [
        'dashboard:read',
        'category:read', 'category:create', 'category:update', 'category:delete',
        'archives:read', 'archives:create', 'archives:update', 'archives:delete',
        'attachment:read', 'attachment:create', 'attachment:update',
        'user:read',
        'system:read'
      ]
    } else {
      console.log('🔧 分配普通用户权限')
      // 普通用户权限
      roles.value = [{
        id: 'r003',
        role_name: '普通用户',
        role_code: 'user',
        status: 'active'
      }]
      
      permissions.value = [
        'dashboard:read',
        'category:read',
        'archives:read'
      ]
    }
    
    console.log('🔧 临时权限分配完成:', { 
      user: userData.realname, 
      roles: roles.value, 
      permissions: permissions.value 
    })
  }

  // 检查权限
  const hasPermission = (permission) => {
    if (!permission) return true
    
    console.log(`🔍 检查权限: ${permission}`)
    console.log('当前权限列表:', permissions.value)
    console.log('当前角色列表:', roles.value)
    
    // 超级管理员拥有所有权限
    if (roles.value.some(role => {
      const roleCode = role.role_code || role.code
      return roleCode === 'super_admin'
    })) {
      console.log('✅ 超级管理员，拥有所有权限')
      return true
    }
    
    // 检查权限数组
    const hasPermissionResult = permissions.value.includes(permission)
    console.log(`权限检查结果: ${hasPermissionResult}`)
    
    return hasPermissionResult
  }

  // 检查角色
  const hasRole = (role) => {
    if (!role) return true
    
    return roles.value.some(r => {
      const roleCode = r.role_code || r.code || r.name || r
      return roleCode === role
    })
  }

  // 检查多个权限（任一匹配）
  const hasAnyPermission = (permissionList) => {
    if (!Array.isArray(permissionList)) return false
    return permissionList.some(permission => hasPermission(permission))
  }

  // 检查多个权限（全部匹配）
  const hasAllPermissions = (permissionList) => {
    if (!Array.isArray(permissionList)) return false
    return permissionList.every(permission => hasPermission(permission))
  }

  // 检查多个角色（任一匹配）
  const hasAnyRole = (roleList) => {
    if (!Array.isArray(roleList)) return false
    return roleList.some(role => hasRole(role))
  }

  // 退出登录
  const doLogout = async () => {
    try {
      console.log('🚪 执行退出登录')
      
      // 调用后端注销接口
      if (hasToken.value) {
        await logoutApi()
      }
    } catch (error) {
      console.error('注销请求失败:', error)
    } finally {
      // 无论后端请求是否成功，都清除本地数据
      token.value = ''
      userInfo.value = {}
      roles.value = []
      permissions.value = []
      
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('roles')
      localStorage.removeItem('permissions')
      localStorage.removeItem('refresh_token')
      
      console.log('✅ 本地数据已清除')
    }
    
    return { 
      success: true, 
      shouldRedirect: '/auth/login',
      message: '已退出登录'
    }
  }

  return {
    token,
    userInfo,
    roles,
    permissions,
    hasToken,
    isLoggedIn,
    login: doLogin,
    getUserInfo: fetchUserInfo,
    logout: doLogout,
    hasPermission,
    hasRole,
    hasAnyPermission,
    hasAllPermissions,
    hasAnyRole
  }
})